package com.yige.web.action

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.ArgsUtil
import com.yige.common.DateUtil
import com.yige.service.mongoService.MongoCostService
import com.yige.service.mongoService.MongoExpenditureService
import com.yige.service.mongoService.MongoLessonService
import com.yige.service.mongoService.MongoLessonStuService
import com.yige.service.mongoService.MongoStudentService
import com.yige.service.mongoService.MongoTeacherService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

import java.text.SimpleDateFormat

/**
 * Created by sunhao on 2016/3/31 0031.
 */
@Controller
@RequestMapping("appTeacher")
class AppTeacherAction {

    @Autowired
    MongoTeacherService teacherService

    @Autowired
    MongoCostService costService

    @Autowired
    MongoLessonService lessonService

    @Autowired
    MongoLessonStuService lessonStuService

    @Autowired
    MongoStudentService studentService

    @Autowired
    MongoExpenditureService expenditureService


    @RequestMapping("findLessons")
    @ResponseBody
    def findLessons(String teacherId) {
        def list = new ArrayList(), lesson
        def teachList = teacherService.findOneById(teacherId).teach
        teachList.each { teach ->
            lesson = lessonService.findOneById(teach).lessons
            lesson.each {
                list.add(it)
            }
        }
        return [msg: true, data: list]
    }

    @RequestMapping("findStudents")
    @ResponseBody
    def findStudents(String teacherId) {
        def list = new ArrayList()
        def studentIds = teacherService.findAllStudentForTeacher(teacherId)
        studentIds.each {
            list.add([id: it, name: this.studentService.findOneById(it).name] as HashMap)
        }
        return [msg: true, data: list]
    }

    @RequestMapping("addLessons")
    @ResponseBody
    def addLessons(String teacherId, String lessonId, String date,
                   @RequestParam(value = "stuIdList") List<String> stuIdList) {
        def student_db = new BasicDBObject(), list
        def cost, ns
        boolean flag = false
        def lesson = lessonStuService.findOneById(lessonId) as DBObject
        //判断课程类型
        if (lesson.status == 0) {//大课
            def stuList = lessonStuService.findStuForLesson(lessonId, teacherId) as ArrayList
            stuList.each { stu ->
                flag = false
                cost = [_id    : UUID.randomUUID().toString(),
                        teacher: teacherId,
                        student: stu._id,
                        lesson : lessonId,
                        pay    : 0] as BasicDBObject
                if (stuIdList.contains(stu._id)) {
                    cost.pay = lesson.price
                }
                flag = saveCost(cost, date)
                //如果课程记录插入成功，改变该学生课费记录
                list = new ArrayList()
                stu.lessons.each {
                    if (lessonId.equals(it.id)) {
                        ns = it.n - 1
                        it.n = ns
                    }
                    list.add(it)
                }
                studentService.updateLessonForStudent(stu._id, list)
            }
        } else if (lesson.status == 1) {//小课
            //添加课费记录和更改学生课程记录
            stuIdList.each { studentId ->
                flag = false
                cost = [_id    : UUID.randomUUID().toString(),
                        teacher: teacherId,
                        student: studentId,
                        lesson : lessonId,
                        pay    : lesson.price] as BasicDBObject
                flag = saveCost(cost, date)
                //如果课程记录插入成功，改变该学生课费记录-1
                list = new ArrayList()
                if (flag) {
                    student_db = studentService.findOneById(studentId)
                    student_db.lessons.each {
                        if (lessonId.equals(it.id)) {
                            ns = it.n - 1
                            it.n = ns
                        }
                        list.add(it)
                    }
                    studentService.updateLessonForStudent(studentId, list)
                }
            }
        } else {//停课
            flag = false
        }
        return [msg: flag]
    }

    @RequestMapping("delLessons")
    @ResponseBody
    def delLessons(String costId) {
        def ns, list = new ArrayList(), student_db
        def cost = costService.findOneById(costId)
        def lessonId = cost.lesson
        def lesson = lessonStuService.findOneById(lessonId) as DBObject
        def flag = false
        if (lesson.status >= 0) {
            //删除课费记录和更改学生课程记录
            flag = costService.deleteOne(costId)
            //如果课程记录删除成功，改变该学生课费记录+1
            if (flag) {
                student_db = studentService.findOneById(cost.student)
                student_db.lessons.each {
                    if (lessonId.equals(it.id)) {
                        ns = it.n + 1
                        it.n = ns
                    }
                    list.add(it)
                }
                studentService.updateLessonForStudent(cost.student, list)
            }
        }
        def cost_db = costService.findListByQueryDesDate([teacher: cost.teacher]as BasicDBObject), count = 0
        list = new ArrayList()
        cost_db.each {
            def obj = [id : it._id, date: DateUtil.formatDate(it.date as Date), teacher: this.teacherService.findOneById(it.teacher).name, flag: false, pay: it.pay,
                       lesson: this.lessonStuService.findOneById(it.lesson).name, student: this.studentService.findOneById(it.student).name]
            if (it.pay == 0) {
                obj.flag = true
            }
            list.add(obj)
            count = count + it.pay
        }
        return [msg: flag, data: list, sum: list.size(), count: count]
    }

    @RequestMapping("findStuByLesson")
    @ResponseBody
    def findStuByLesson(String teacherId, String lessonId) {
        def students = new ArrayList()
        def stuList = lessonStuService.findStuForLesson(lessonId, teacherId) as ArrayList
        stuList.each {
            students.add([id: it._id, name: it.name] as BasicDBObject)
        }
        return [msg: true, data: students]
    }

    @RequestMapping("findCost")
    @ResponseBody
    def findCost(String teacherId, String lessonId, String studentId, String startDate, String endDate) {
        def query = new BasicDBObject(), list = new ArrayList()
        def sdf = new SimpleDateFormat("yyyy-MM-dd")
        if (!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
            query.append("date", [$gte: sdf.parse(startDate), $lte: sdf.parse(endDate)] as BasicDBObject)
        } else if (!StringUtils.isEmpty(startDate) && StringUtils.isEmpty(endDate)) {
            query.append("date", [$gte: sdf.parse(startDate)] as BasicDBObject)
        } else if (StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
            query.append("date", [$lte: sdf.parse(endDate)] as BasicDBObject)
        }
        if (!StringUtils.isEmpty(teacherId)) {
            query.append("teacher", teacherId)
        }
        if (!StringUtils.isEmpty(lessonId)) {
            query.append("lesson", lessonId)
        }
        if (!StringUtils.isEmpty(studentId)) {
            query.append("student", studentId)
        }
        def cost = costService.findListByQueryDesDate(query), count = 0
        cost.each {
            def obj = [id  : it._id, date: DateUtil.formatDate(it.date as Date), teacher: this.teacherService.findOneById(it.teacher).name, flag: false, pay: it.pay,
                       lesson: this.lessonStuService.findOneById(it.lesson).name, student: this.studentService.findOneById(it.student).name]
            if (it.pay == 0) {
                obj.flag = true
            }
            list.add(obj)
            count = count + it.pay
        }
        return [msg: true, data: list, sum: list.size(), count: count]
    }

    @RequestMapping("findSalary")
    @ResponseBody
    def findSalary(String teacherId) {
        def salary = expenditureService.findListByQuery([teacher: teacherId] as BasicDBObject)
        def list = new ArrayList(), date
        def sdf = new SimpleDateFormat("yyyy-MM-dd")
        def total = 0.0
        salary.each {
            def way = "现金"
            if (it.way == 1) {
                way = "转账"
            }
            total = total + it.pay
            date = sdf.format(it.date)
            list.add([pay    : it.pay, description: it.description, way: way, date: date,
                      teacher: this.teacherService.findOneById(teacherId).name])
        }
        return [msg: true, data: list, count: total]
    }

    /*************方法模块***************/

    def saveCost(DBObject costInfo, String date) {
        ArgsUtil.checkArgs(costInfo)
        DBObject cost_db = costService.findOneById(costInfo._id)
        if (cost_db == null) {
            costInfo.put("date", DateUtil.parseDate(date))
            costService.insertOne(costInfo)
            return true
        } else {
            return false
        }
    }
}
